今天我們就用昨天生成好的gRPC程式來把我們的實作完成吧
首先我們的server端會寫成這個樣子,透過樣板程式來監聽我們的Client端
@Override
public StreamObserver<TransferRequest> Transfer(StreamObserver<TransferResponse> responseObserver) {
return new StreamObserver<TransferRequest>() {
@Override
public void onNext(Request Request) {
System.out.println("接收到client端的訊息: " + Request.getId());
System.out.println("接收到client端的訊息: " + Request.getAddress());
System.out.println("接收到client端的訊息: " + Request.getName());
System.out.println("接收到client端的訊息: " + Request.getCount());
System.out.println("接收到client端的訊息: " + Request.getSentTime());
System.out.println("====");
}
@Override
public void onError(Throwable throwable) {
System.out.println("我沒有收到client端的訊息");
}
@Override
public void onCompleted() {
System.out.println("client的訊息全部都發送到server端");
TransferResponse transferResponse = TransferResponse.newBuilder().build();
responseObserver.onNext(Response);
responseObserver.onCompleted();
}
};
}
然後我們的Client端則是做成這樣,那我們還另外使用了GSON模組,將我們的資料轉換成json格式,並且讀取json格式的資料。
//設計好連線資訊
String host = "localhost";
int port = 5000;
//通訊管道建立
ManagedChannel managedChannel = ManagedChannelBuilder.forAddress(host,port).usePlaintext().build();
//判斷是否有連線成功
if (managedChannel != null && !managedChannel.isShutdown())
System.out.println(" channel build success !! " + host + ":" + port);
//建立連線
try{
TransferServiceGrpc.TransferServiceStub service = TransferServiceGrpc.newStub(managedChannel);
StreamObserver<Request> requestStreamObserver =
service.trafficTransfer(new StreamObserver<Response>() {
@Override
public void onNext(Response Response) {
System.out.println("我是傳送出去的訊息: " + Response.getMessage());
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
});
for(int i = 0 ; i < excel_data.toArray().length ; i++){
JsonObject json = gson.toJsonTree(excel_data.get(i)).getAsJsonObject();
//設定傳送資訊
Request request = Request.newBuilder()
.setId(json.get("id").getAsString())
.setCount(json.get("count").getAsString())
.setAddress(json.get("address").getAsString())
.setName(json.get("name").getAsString())
.setSentTime(json.get("sentTime").getAsString())
.build();
requestStreamObserver.onNext(request);
}
//因為非阻塞(newStub) 因此client會立刻關閉 需要等待一些時間 等server傳資料過來
managedChannel.awaitTermination(10, TimeUnit.SECONDS);
//傳送完成的訊號給server
requestStreamObserver.onCompleted();
} catch (Exception e){
e.printStackTrace();
} finally {
//關閉連線
managedChannel.shutdown();
}
} catch (Exception e){
e.printStackTrace();
}
到這邊為止就大功告成了,我們將excel資料透過POI模組讀取進來後,再將檔案轉成json格式,並且把資料讀取進來傳送。